using System;
using System.Linq;

namespace ECatalog.Models.ModelSizes
{
    public class ModelSizeRepository : IModelSizeRepository
    {
        public void Remove(int modelsizeid)
        {
            using (var db = new DbContainer())
            {
                var c = db.ModelSizes.SingleOrDefault(st => st.ModelSizeId == modelsizeid);
                if (c != null)
                {
                    try
                    {
                        db.ModelSizes.Remove(c);
                        db.SaveChanges();
                    }
                    catch (Exception)
                    {

                    }
                }
            }
        }

        public ModelSize Add(ModelSize modelSize, string value)
        {
            using (var db = new DbContainer())
            {
                try
                {
                    var size = db.Sizes.FirstOrDefault(s => s.Value.ToUpper() == value.ToUpper());
                    if (size == null)
                    {
                        size = new Size
                            {
                                Value = value.ToUpper()
                            };
                        db.Sizes.Add(size);
                        db.SaveChanges();
                    }
                    modelSize.SizeId = size.SizeId;
                    db.ModelSizes.Add(modelSize);
                    db.SaveChanges();
                }
                catch (Exception)
                {

                }
                return db.ModelSizes.Include("Size").Include("Shop").FirstOrDefault(m => m.ModelSizeId == modelSize.ModelSizeId);
            }
        }
    }
}